package com.czy.utilslib.network;



import androidx.annotation.NonNull;
import com.czy.utilslib.debug.DebugUtil;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class LoggingInterceptor implements Interceptor {

    private final String TAG = LoggingInterceptor.class.getSimpleName();

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        long startTime = System.nanoTime();

        // 打印请求信息
        DebugUtil.logV(TAG,"\n\n----> Request");
        DebugUtil.logV(TAG,"URL: " + request.url());
        DebugUtil.logV(TAG,"Method: " + request.method());
        //DebugUtil.logV(TAG,"Headers: " + request.headers());
        if(request.body() != null){
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            DebugUtil.logI(TAG, "\n\n----> RequestBody -> " + buffer.readUtf8());
        }
        else {
            DebugUtil.logV(TAG,"request.body() == null");
        }

        Response response = chain.proceed(request);
        long endTime = System.nanoTime();

        // 打印响应信息
        DebugUtil.logV(TAG,"\n\n<---- Response (" + (endTime - startTime) / 1e6d + "ms)");
        DebugUtil.logV(TAG,"Status Code: " + response.code());
        //DebugUtil.logV(TAG,"Headers: " + response.headers());


        ResponseBody responseBody = response.body();
        String responseBodyString = null;
        if (responseBody != null) {
            responseBodyString = responseBody.string();
            DebugUtil.logI(TAG, "\n\n<---- ResponseBody: " + responseBodyString);
        }
        else {
            responseBodyString = "";
        }

        return response.newBuilder()
                .body(ResponseBody.create(MediaType.parse("UTF-8"), responseBodyString))
                .build();
    }

}
